package com.wtwd.wtwddevice.listener.deviceServerMsg.handler.impl;

import com.wtwd.device.annotation.MsgType;
import com.wtwd.device.constant.AlarmHealthConstant;
import com.wtwd.device.constant.AnswerStateEnum;
import com.wtwd.device.constant.MsgTypeEnum;
import com.wtwd.device.constant.SeparatorConstant;
import com.wtwd.device.mqtentity.MessageBase;
import com.wtwd.device.protocol.WTProtocol;
import com.wtwd.device.util.DateUtils;
import com.wtwd.wtwddevice.listener.deviceServerMsg.handler.IMsgHandler;
import com.wtwd.wtwddevice.model.entity.AlarmHealth;
import com.wtwd.wtwddevice.mq.PushMsgService;
import com.wtwd.wtwddevice.service.IAlarmHealthService;
import com.wtwd.wtwddevice.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@MsgType(MsgTypeEnum.ALARM_HEALTH)
@Component
public class AlarmHealthHandlerImpl implements IMsgHandler {
    @Autowired
    private IAlarmHealthService alarmHealthService;

    @Resource
    private PushMsgService msgService;

    @Autowired
    private IDeviceService deviceService;

    @Override
    public void handleMsg(MessageBase messageBase) {
        WTProtocol wtProtocol = messageBase.getWtProtocol();
        Long deviceId = deviceService.getDeviceIdByImei(wtProtocol.getImei());
        String[] split = wtProtocol.getBody().split(SeparatorConstant.CMD_BODY_SEGMENTATION);

        AlarmHealth alarmHealth = new AlarmHealth();
        alarmHealth.setDeviceId(deviceId);
        alarmHealth.setType(Byte.valueOf(split[0]));

        if(split[0].equals(AlarmHealthConstant.HR_EXCEPTION)){
            alarmHealth.setHrData(split[1]);
        }else if(split[0].equals(AlarmHealthConstant.OX_EXCEPTION)){
            alarmHealth.setOxData(split[1]);
        }else if(split[0].equals(AlarmHealthConstant.BP_EXCEPTION)){
            String[] bp = split[1].split(SeparatorConstant.LOCATION_SPLIT);
            alarmHealth.setDiastolicPressure(bp[0]);
            alarmHealth.setSystolicPressure(bp[1]);
        }

        alarmHealth.setNumber(wtProtocol.getNumber());
        alarmHealth.setTime(wtProtocol.getTime());
        alarmHealth.setCreateTime(System.currentTimeMillis());
        alarmHealth.setUpdateTime(System.currentTimeMillis());

        alarmHealthService.addAlarmHealth(alarmHealth);

        wtProtocol.setTime(wtProtocol.getTime());
        wtProtocol.setBody(String.valueOf(AnswerStateEnum.NORMAL.getState()));
        wtProtocol.setBodyLength(wtProtocol.getBody().length());
        msgService.pushToDevice(messageBase.getForm(),
                MessageBase.builder().deviceKey(wtProtocol.getImei())
                        .wtProtocol(wtProtocol)
                        .build());
    }
}
